#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统一配置管理
"""

from typing import Dict, List, Any
from enum import Enum


class ChartType(Enum):
    """支持的图表类型"""
    LINE = "line"
    BAR = "bar"
    PIE = "pie"
    SCATTER = "scatter"
    AREA = "area"
    TABLE = "table"


# 图表配置统一管理
CHART_CONFIGS = {
    "line": {
        "name": "折线图",
        "description": "显示数据变化趋势",
        "echarts_type": "line",
        "required_fields": ["x_field", "y_field"],
        "default_config": {
            "smooth": True,
            "symbol": "circle",
            "symbolSize": 6
        }
    },
    "bar": {
        "name": "柱状图",
        "description": "比较不同类别数值",
        "echarts_type": "bar",
        "required_fields": ["x_field", "y_field"],
        "default_config": {
            "barWidth": "60%"
        }
    },
    "pie": {
        "name": "饼图",
        "description": "显示占比关系",
        "echarts_type": "pie",
        "required_fields": ["name_field", "value_field"],
        "default_config": {
            "radius": ["0%", "70%"],
            "center": ["50%", "60%"]
        }
    },
    "scatter": {
        "name": "散点图",
        "description": "显示变量关系",
        "echarts_type": "scatter",
        "required_fields": ["x_field", "y_field"],
        "default_config": {
            "symbolSize": 8
        }
    },
    "area": {
        "name": "面积图",
        "description": "显示累积趋势",
        "echarts_type": "line",
        "required_fields": ["x_field", "y_field"],
        "default_config": {
            "areaStyle": {"opacity": 0.6},
            "smooth": True
        }
    },
    "table": {
        "name": "表格",
        "description": "显示详细数据",
        "echarts_type": None,
        "required_fields": [],
        "default_config": {
            "pagination": True,
            "pageSize": 10
        }
    }
}

# 数据处理模板
PROCESSING_TEMPLATES = {
    "filter": "df = df.query('{condition}')",
    "group_sum": "df = df.groupby('{group_field}')['{value_field}'].sum().reset_index()",
    "group_mean": "df = df.groupby('{group_field}')['{value_field}'].mean().reset_index()",
    "group_count": "df = df.groupby('{group_field}').size().reset_index(name='count')",
    "sort_asc": "df = df.sort_values('{field}', ascending=True)",
    "sort_desc": "df = df.sort_values('{field}', ascending=False)",
    "limit": "df = df.head({limit})"
}


class ConfigManager:
    """配置管理器"""
    
    @staticmethod
    def get_chart_config(chart_type: str) -> Dict[str, Any]:
        """获取图表配置"""
        return CHART_CONFIGS.get(chart_type, CHART_CONFIGS["table"])
    
    @staticmethod
    def get_all_chart_types() -> List[str]:
        """获取所有图表类型"""
        return list(CHART_CONFIGS.keys())
    
    @staticmethod
    def is_valid_chart_type(chart_type: str) -> bool:
        """验证图表类型"""
        return chart_type in CHART_CONFIGS
    
    @staticmethod
    def get_processing_template(template_name: str) -> str:
        """获取处理模板"""
        return PROCESSING_TEMPLATES.get(template_name, "")
    
    @staticmethod
    def get_prompt_template(prompt_name: str) -> str:
        """获取提示词模板"""
        # 导入优化后的提示词模板
        try:
            from data_engine.templates.prompts.chart_analysis import (
                CHART_ANALYSIS_PROMPT, 
                DATA_PROCESSING_PROMPT,
                ECHARTS_GENERATION_PROMPT,
                TABLE_GENERATION_PROMPT
            )
            
            templates = {
                "chart_analysis": CHART_ANALYSIS_PROMPT,
                "data_processing": DATA_PROCESSING_PROMPT,
                "echarts_generation": ECHARTS_GENERATION_PROMPT,
                "table_generation": TABLE_GENERATION_PROMPT
            }
            
            return templates.get(prompt_name, "")
            
        except ImportError:
            # 备用简单模板
            fallback_templates = {
                "chart_analysis": """
根据数据和问题，分析需要什么图表类型。

数据信息：
- 数据形状：{data_shape}
- 字段列表：{columns}
- 数据样例：{sample_data}

用户问题：{question}

支持的图表类型：
{chart_types_info}

请分析并返回JSON格式：
{{
    "chart_type": "图表类型",
    "need_chart": true/false,
    "x_field": "x轴字段",
    "y_field": "y轴字段",
    "name_field": "名称字段(饼图用)",
    "value_field": "数值字段(饼图用)",
    "group_by": "分组字段",
    "aggregation": "聚合方式",
    "sort_by": "排序字段",
    "sort_order": "asc/desc",
    "limit": 行数限制,
    "confidence": 0.95,
    "reasoning": "分析原因"
}}
""",
                "data_processing": """
生成pandas数据处理代码。

数据信息：{data_info}
处理要求：{requirements}

请生成Python代码，输入输出变量都是df：
""",
                "echarts_generation": """
根据数据生成ECharts配置。

图表类型：{chart_type}
数据：{processed_data}
字段映射：{field_mapping}

请生成标准ECharts JSON配置。
""",
                "table_generation": """
根据数据生成表格配置。

数据：{processed_data}
字段描述：{field_descriptions}

请生成表格JSON配置。
"""
            }
            return fallback_templates.get(prompt_name, "")
    
    @staticmethod
    def build_chart_types_info() -> str:
        """构建图表类型信息"""
        info_lines = []
        for chart_type, config in CHART_CONFIGS.items():
            info_lines.append(f"- {chart_type}: {config['name']} - {config['description']}")
        return "\n".join(info_lines) 